package com.guangwei.lockscreenforelder.lockscreen

import android.app.Service
import android.app.Service.START_STICKY
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.util.Log

class LockScreenService : Service() {
    private var mReceiver: BroadcastReceiver? = null

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()

        Log.i("LockScreenService", "LockScreenService: onCreate********")

        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_SCREEN_ON)
        filter.addAction(Intent.ACTION_SCREEN_OFF)
        filter.addAction(Intent.ACTION_BOOT_COMPLETED)

        mReceiver = LockScreenReceiver()
        registerReceiver(mReceiver, filter)
    }

    override fun onDestroy() {
        super.onDestroy()

        Log.i("LockScreenService", "LockScreenService: onDestroy********")

        unregisterReceiver(mReceiver)

        // No sure why the service exit, we want to force this serve always running
        // When get destroy information, re-launch the service
        //startLockScreenService(this)
        //startService(Intent(this, LockScreenService::class.java))
        LockScreenServiceGuider.startLockScreenServiceGuider(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val onStartCommand = super.onStartCommand(intent, flags, startId)
        Log.i("LockScreenService", "LockScreenService: onStartCommand********")
        return START_STICKY
    }



    companion object {
        fun startLockScreenService(context: Context){
            val intent = Intent()
            intent.setClass(context, LockScreenService::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            //context.startService(intent)
            context.startService(intent)
            Log.i("LockScreenService", "LockScreenService: startLockScreenService********")
        }

        fun stopLockScreenService(context: Context) {
            val intent = Intent()
            intent.setClass(context, LockScreenService::class.java)
            context.stopService(intent)
        }
    }
}
